<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div>
          <el-input
            v-model="name"
            placeholder="请输入分类名称"
            clearable
            icon="Search"
            style="margin-bottom: 20px"
          />
          <el-tree
            ref="treeRef"
            :data="classify"
            :props="defaultProps"
            default-expand-all
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            @node-click="selectArticle"
          ></el-tree>
        </div>
      </el-col>
      <el-col :span="20" :xs="24" style="border-left:thin solid #c4bebe;">
        <el-form ref="queryForm" :model="queryParams" :inline="true" style="margin-bottom: 50px;">
          <el-form-item label="文章标题" prop="name">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入文章标题"
              clearable
              style="width: 200px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="文章状态" prop="configKey">
            <el-select
              v-model="queryParams.status"
              placeholder="文章状态"
              clearable
              style="width: 120px;"
            >
              <el-option label="已发布" value="0"></el-option>
              <el-option label="未发布" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" prop="status">
            <el-date-picker
              v-model="queryParams.dateRange"
              el-date-picker
              placeholder="创建时间"
              unlink-panels
              type="daterange"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
            ></el-date-picker>
          </el-form-item>
          <el-form-item :inline="true" style="float: right;">
            <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
            <el-button icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
        <div>
          <el-button type="primary" plain size="small" icon="Plus" @click="handleAdd">新增</el-button>
          <el-button type="danger" plain size="small" icon="Delete" @click="handleDelete">删除</el-button>
          <el-button plain size="small" @click="handleRelease('0', {})">
            <icon-svg iconClass="release"></icon-svg>&nbsp;发布
          </el-button>
          <el-button plain size="small" @click="handleRelease('1', {})">
            <icon-svg iconClass="offTheShelf"></icon-svg>&nbsp;下架
          </el-button>
        </div>
        <el-table
          :data="ArticleList"
          v-loading="loading"
          stripe
          ref="multipleTableRef"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="title" label="标题" align="center" />
          <el-table-column prop="sort" label="排序" align="center" />
          <el-table-column prop="isComment" label="是否评论" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.isComment"
                active-value="0"
                inactive-value="1"
                inline-prompt
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否"
                @click="updateIsComment(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center">
            <template #default="scope">{{ scope.row.status === '0' ? '已发布' : '未发布' }}</template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" width="200" />
          <el-table-column label="操作" align="center" width="200">
            <template #default="scope">
              <el-button size="small" type="text" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="small" type="text" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
              <el-button
                v-if="scope.row.status === '1'"
                size="small"
                type="text"
                icon="Delete"
                @click="handleRelease('0', scope.row)"
              >发布</el-button>
              <el-button
                v-if="scope.row.status === '0'"
                size="small"
                type="text"
                icon="Delete"
                @click="handleRelease('1', scope.row)"
              >下架</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pageClass">
          <el-pagination
            :hide-on-single-page="true"
            v-model:currentPage="queryParams.current"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="queryParams.size"
            :pager-count="11"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>

    <!-- 文章添加和修改 -->
    <article-form ref="articleForm" @refreshArticle="loadList" />
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, reactive, onMounted } from 'vue'
import type { ElTree } from 'element-plus'
import type { Article, AueryType } from '@/api/types/article'
import ArticleForm from '@/views/Article/List/module/ArticleForm.vue'
import { getClassifyTree } from '@/api/classify'
import { pageList, deleteByIds, releaseByIds, updateComment } from '@/api/article'

interface Tree {
  value: number
  label: string
  children?: Tree[]
  allow: boolean
}

const queryParams = reactive<AueryType>({
  current: 1,
  size: 10,
  pid: undefined,
  title: undefined,
  status: undefined,
  dateRange: undefined
})

const defaultProps = {
  children: 'children',
  label: 'label',
  disabled: 'allow'
}

const name = ref('')

const treeRef = ref<InstanceType<typeof ElTree>>()

const articleForm = ref()

const ArticleList = ref<Article[]>([])

const loading = ref(false)

const multipleSelection = ref<(number | undefined)[]>([])

const multipleSelectionName = ref<string[]>([])

const classify = ref<Tree[]>()

const total = ref(0)

const shortcuts: [] = []

watch(name, (val) => {
  treeRef.value!.filter(val)
})

onMounted(() => {
  loadList()
  loadClassifyList()
})

const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

/**
 * 加载表格数据
 */
const loadList = async () => {
  loading.value = true
  const articlePage = await pageList(queryParams)
  ArticleList.value = articlePage.records
  total.value = articlePage.total
  loading.value = false
}

/**
 * 加载树结构分类目录
 */
const loadClassifyList = async () => {
  classify.value = await getClassifyTree(1)
}

/**
 * 根据选择分类展示文章
 */
const selectArticle = async (node: Tree) => {
  queryParams.pid = node.value
  loadList()
}

/**
 * 查询数据
 */
const handleSearch = () => {
  loadList()
}

/**
 * 重置查询条件
 */
const handleReset = () => {
  queryParams.pid = undefined
  queryParams.title = undefined
  queryParams.dateRange = undefined
  queryParams.status = undefined
  queryParams.current = 1
  queryParams.size = 10
  loadList()
}

/**
 * 更改页容量事件
 * @param val 
 */
const handleSizeChange = (val: number) => {
  queryParams.size = val
  loadList()
}

/**
 * 换页事件
 * @param val 
 */
const handleCurrentChange = (val: number) => {
  queryParams.current = val
  loadList()
}

/**
 * 多选事件
 * @param val 
 */
const handleSelectionChange = (val: Article[]) => {
  multipleSelection.value = val.map(item => item.articleId)
  multipleSelectionName.value = val.map(item => item.title)
}

/**
 * 打开文章添加对话框
 */
const handleAdd = () => {
  articleForm.value.openForm()
}

/**
 * 打卡文章修改对话框
 */
const handleUpdate = (article: Article) => {
  articleForm.value.openForm(article)
}

/**
 * 删除文章
 * @param article 
 */
const handleDelete = async (article: Article | any) => {
  let isDelete;
  let ids = article.articleId || multipleSelection.value
  let message = article.title ? article.title : String(multipleSelectionName.value)
  if (ids && ids.length !== 0) {
    try {
      await ElMessageBox.confirm(
        '是否要删除:' + message,
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      isDelete = await deleteByIds(ids)
      if (isDelete) {
        loadList()
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
      } else {
        ElMessage({
          message: '请选择删除数据',
          type: 'error',
        })
      }
    } catch (err) {

    }

  } else {
    ElMessage({
      message: '请选择删除数据',
      type: 'error',
    })
  }
}

/**
 * 发布文章
 * @param article 
 */
const handleRelease = async (status: string, article: Article | any) => {
  let isRelease;
  let ids = article.articleId || multipleSelection.value
  let message;
  let errorMessage;
  let successMessage;
  if (status === '0') {
    message = '是否要发布'
    errorMessage = '请选择发布数据'
    successMessage = '发布成功'
  } else if (status === '1') {
    message = '是否要下架'
    errorMessage = '请选择下架数据'
    successMessage = '下架成功'
  }
  message += article.title ? article.title : String(multipleSelectionName.value)
  if (ids && ids.length !== 0) {
    try {
      await ElMessageBox.confirm(
        message,
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      isRelease = await releaseByIds(ids, status)
      if (isRelease) {
        loadList()
        ElMessage({
          message: successMessage,
          type: 'success',
        })
      } else {
        ElMessage({
          message: errorMessage,
          type: 'error',
        })
      }
    } catch (err) {

    }

  } else {
    ElMessage({
      message: errorMessage,
      type: 'error',
    })
  }
}

const updateIsComment = async (article: Article) => {
  const isUpdate = await updateComment(article).finally(() => {
    loadList()
  })
  if (isUpdate) {
    ElMessage({
      message: '修改成功',
      type: 'success',
    })
  }
}
</script>
